package P10_Fork_Join_分支合并框架;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class P02_ForkJoinDemo {

//    public static void main(String[] args) {
//        MyTask task = new MyTask(1, 100);
//        System.out.println(task.compute()); // 5050
//    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask task = new MyTask(1, 100);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(task);
        System.out.println(forkJoinTask.get()); // 5050
        forkJoinPool.shutdown();
    }
}

class MyTask extends RecursiveTask<Integer> {

    private static final Integer DIFF = 10;
    private Integer begin;
    private Integer end;
    private Integer result = 0;

    public MyTask(Integer begin, Integer end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if (end - begin <= DIFF) {
            for (int i = begin; i <= end; i++) {
                result += i;
            }
        } else {
            int middle = (begin + end) / 2;
            MyTask task1 = new MyTask(begin, middle);
            task1.fork();
            MyTask task2 = new MyTask(middle + 1, end);
            result = task2.compute() + task1.join();
        }
        return result;
    }
}
